﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using EntityManage;
using BusinessFacade;

public partial class Modules_Personal_PerfApplyAdd : System.Web.UI.Page
{
    IPerf_Personal_EvaluateHandler evaHandler = new Perf_Personal_EvaluateManage();
    IPerf_Personal_EvaluateHandlerExt evaExtHandler = new Perf_Personal_EvaluateManageExt();
    IPerf_Flow_TraceHandler flowTraceHandler = new Perf_Flow_TraceManage();
    IPerf_Personal_ApprovalHandler approvalHandler = new Perf_Personal_ApprovalManage();
    ISys_ConfigHandler configHandler = new Sys_ConfigManage();
    IPerf_Flow_StepsHandler flowStepHandler = new Perf_Flow_StepsManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("303020"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        float bascScore = 100;

        //获取配置的基准分
        Sys_ConfigQuery qConfig = configHandler.GetSys_ConfigQuery(1);
        if (qConfig != null)
        {
            bascScore = float.Parse(qConfig.ConfigValue);
        }

        if (Session["UserPurviews"] != null && Session["UserPurviews"].ToString().Contains("303020"))
        {
            List<string> ids = new List<string>();
            string[] evalIds = Request["evalIds"].Split(',');
            ids.AddRange(evalIds);

            if (ids.Count > 0)
            {
                int userId = int.Parse(Session["CurrentUserID"].ToString());
                Perf_Personal_EvaluateQuery[] evalList = evaHandler.GetPerf_Personal_EvaluateQueryList(" ID in (" + Request["evalIds"] + ")", new SqlParameter[]{});
                List<string> uidList = new List<string>();
                List<string> scoreList = new List<string>();    // 格式：分数,次数,evalID0|evalID1|....

                foreach (Perf_Personal_EvaluateQuery evalQuery in evalList)
                {
                    if (!uidList.Contains(evalQuery.Target_User_ID.ToString()))
                    {
                        uidList.Add(evalQuery.Target_User_ID.ToString());
                        float score = evaExtHandler.GetTotalScore(evalQuery.ID);
                        scoreList.Add((bascScore + score) + ",1," + evalQuery.ID);
                    }
                    else
                    {
                        int idx = uidList.LastIndexOf(evalQuery.Target_User_ID.ToString());
                        string[] tmps = scoreList[idx].Split(',');
                        float score = evaExtHandler.GetTotalScore(evalQuery.ID);
                        score = score + bascScore + int.Parse(tmps[0]);
                        int times = int.Parse(tmps[1]);

                        scoreList[idx] = score + "," + (times + 1) + "," + tmps[2] + "|" + evalQuery.ID;
                    }
                }

                for (int i = 0; i < uidList.Count; i++ )
                {
                    string[] scores = scoreList[i].Split(',');
                    // 添加到绩效呈批表
                    int approvalId = 0;
                    Perf_Personal_ApprovalQuery appQuery = new Perf_Personal_ApprovalQuery();
                    appQuery.User_ID = userId;
                    appQuery.Target_User_ID = int.Parse(uidList[i]);
                    appQuery.Perf_Date = DateTime.Parse(txtPerfDate.Value);
                    appQuery.Begin_Time = DateTime.Parse(txtPerfDate.Value);//appQuery.Perf_Date;
                    appQuery.End_Time = DateTime.Parse(txtEndDate.Value);//appQuery.Perf_Date;
                    appQuery.Score = (double.Parse(scores[0]) / (int.Parse(scores[1])));

                    //添加评分ID集
                    appQuery.EvaluateIDs = ids[i];

                    //////////////////////  TODO: 添加任务得分//////////////
                    appQuery.Task_Score = 0;
                    appQuery.Title = txtTitle.Text;
                    //if (!"".Equals(txtPlusScore.Text))
                    //{
                    //    appQuery.Plus_Score = double.Parse(txtPlusScore.Text);
                    //}
                    appQuery.Plus_Score = 0;
                    appQuery.Plus_Reason = string.Empty;// txtPlusReason.Text;
                    //if (!"".Equals(txtNoticeLen.Text))
                    //    appQuery.Notice_Len = int.Parse(txtNoticeLen.Text);
                    //else
                        appQuery.Notice_Len = 5;

                    //if (!"".Equals(txtAppvalLen.Text.Trim()))
                    //    appQuery.Appeal_Len = int.Parse(txtAppvalLen.Text);
                    //else
                        appQuery.Appeal_Len = 5;
                    appQuery.Status = (int)Enums.PersonalApprovalStatus.NewAdded;
                    appQuery.Remark = txtRemark.Text;
                    appQuery.Create_Time = DateTime.Now;
                    approvalHandler.InsertPerf_Personal_Approval(appQuery, ref approvalId);

                    if (approvalId != 0)
                    {
                        // 添加到流程跟踪表
                        Perf_Flow_TraceQuery ftQuery = new Perf_Flow_TraceQuery();
                        ftQuery.Flow_ID = (int)Enums.PerfFlowIDs.PersonalEvaluateApproval;
                        ftQuery.Business_ID = approvalId;
                        ftQuery.URL = Enums.Personal_Evaluate_Flow_Form_URL;
                        ftQuery.Begin_Time = DateTime.Now;
                        ftQuery.Current_Step = 1;//添加第一步

                        int current_StepID = 0;
                        Perf_Flow_StepsQuery[] querys = flowStepHandler.GetPerf_Flow_StepsQueryList("Flow_ID=@Flow_ID and IsEnable=@IsEnable", new SqlParameter[] { new SqlParameter("@Flow_ID", (int)Enums.PerfFlowIDs.PersonalEvaluateApproval), new SqlParameter("@IsEnable", 1) }, " Step_Num asc");
                        if (querys != null && querys.Length > 0)
                        {
                            current_StepID = querys[0].ID;
                        }
                        ftQuery.Current_Step_ID = current_StepID;

                        int flowTraceId = 0;
                        flowTraceHandler.InsertPerf_Flow_Trace(ftQuery, ref flowTraceId);

                        if (flowTraceId != 0)
                        {
                            appQuery = approvalHandler.GetPerf_Personal_ApprovalQuery(approvalId);
                            appQuery.Flow_Trace_ID = flowTraceId;
                            approvalHandler.UpdatePerf_Personal_Approval(appQuery);
                        }

                        // 更新评分表的状态和approval_id
                        string[] eids = scores[2].Split('|');
                        foreach (string eid in eids)
                        {
                            Perf_Personal_EvaluateQuery eq = evaHandler.GetPerf_Personal_EvaluateQuery(int.Parse(eid));
                            eq.Status = (int)Enums.PersonalEvaluateStatus.Apply;
                            eq.Approval_ID = approvalId;
                            evaHandler.UpdatePerf_Personal_Evaluate(eq);
                        }
                    }
                }
            }
        }
        Jscript.Alert("呈批成功",this.Page);
        Jscript.ReturnAndClose(this.Page, "true");
    }

}
